﻿using System;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;

namespace senController.classes
{    
    class NetworkReader
    {
        private NetworkController _networkController;
        private NetworkStream _stream;

        private bool _switchMode;

        public NetworkReader(NetworkStream stream, NetworkController networkController, bool mode)
        {
            this._networkController = networkController;
            this._stream = stream;
            this._switchMode = mode;
        }
        public Thread Prepare()
        {
            return new Thread(new ThreadStart(Listen));
        }
        private void Listen()
        {
            try
            {
                BinaryReader clientStreamR = new BinaryReader(new BufferedStream(_stream, 1024), Encoding.ASCII);
                while (true)
                {
                    //Ontvang een command van de client.
                    //De buffered stream zorgt er voor dat we de command als 1 pakketje sturen ipv 3.
                           
                    byte cmd = clientStreamR.ReadByte();
                    int length = (_switchMode) ? clientStreamR.ReadInt32() : clientStreamR.ReadByte() ; //clientStreamR.ReadByte(); (JAVA FIX) //ReadInt32
                    string arg = new string(clientStreamR.ReadChars(length));

                    Console.WriteLine("Command recieved {0}, with arguments: {1}", cmd, arg);
                    _networkController.ProccesIncommingCommand(cmd, arg);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }

        /// <summary>
        /// Switch network mode between readbyte and readint
        /// </summary>
        /// <param name="value">current switch value</param>
        public void switchMode(bool value)
        {
            this._switchMode = value;
        }
    }
}